import 'dart:convert';

import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/services.dart';
import 'package:ls_work/net/api/http_api.dart';
import 'package:ls_work/net/response/config_url_response.dart';
import 'package:ls_work/net_configs.dart';
import 'package:saas_order_meal/saas_order_meal.dart';
import 'package:visitor_scan_package/net/api.dart';

class RequestUrlUtils {
  static String code = "";
  static String orgName = "";
  static String branchId = "";
  // static const String _configUrl = "https://gitee.com/code1993/sale-api/raw/master/sm2json";
  static const String _configUrl = "http://zhyly_api.yytong.com/szky.js";
  static List<ConfigUrlResponse> urlList = [];
  static bool _debug = false;
  static ConfigUrlResponse? currentOrg;
  static void init({bool debug = false}) {
    code = SpUtil.getString("code", defValue: "")??"";
    _debug = debug;
  }

  static void saveCode(String code) {
    SpUtil.putString("code", code);
  }

  static Future<List<ConfigUrlResponse>> requestUrl() async {
    var jsonStr = "";
    if(!useLocalUrl){
       jsonStr = await HttpGo.instance.getDataString(_configUrl);
    }else{
      // jsonStr = await rootBundle.loadString("assets/url_path.json");
    }
    var data = jsonDecode(jsonStr);
    urlList = data == null
        ? []
        : (data as List).map((e) {
          var bean = ConfigUrlResponse.fromJson(e);
          if(BuildConfig.isDebug){
            if(bean.code=="gfszky"){
              bean.api = "http://kytest.yytong.com/ophApi/";
            }
          }
          return bean;
    }).toList();
    return urlList;
  }

  static Future<ConfigUrlResponse?> findUrl(String code) async {
    if(_debug){
      return Future.value(null);
    }
    if(code.isNullOrEmpty()){
      return Future.value(null);
    }
    if (urlList.isEmpty) {
      try{
        await requestUrl();
      }catch(e){
        urlList = localMap.map((e)=>ConfigUrlResponse.fromJson(e)).toList();
      }
    }
    ConfigUrlResponse? url;
    for (var item in urlList) {
      if ((item.code??"").trim() == code.trim()) {
        url = item;
        RequestUrlUtils.code = code.trim();
        branchId = item.branchId.toString();
        saveCode(code.trim());
        break;
      }
    }
    if(url==null){
      HttpApi.baseUrl = "";
      Apis.base_url = "";
      HttpApi.approveUrl = "";
      orgName = "";
    }else{
      HttpApi.baseUrl = url.api??"";
      Apis.base_url = url.api??"";
      HttpApi.approveUrl = url.root??"";
      orgName = url.name??"";
    }
    SaasOrderMeal.initBaseUrl(url?.api??"");

    currentOrg = url;
    return url;
  }

  static List<Map<String,dynamic>> localMap = [
    {
      "code": "gfuat1",
      "name":"广发uat1",
      "api":"https://decs-fs.gf.com:7312/ophApi/",
      "root":"https://decs-fs.gf.com:7312/",
    }
  ];
}
